<?php
namespace app\company\model;


use app\mini\job\order\Confirm;
use app\service\order\Cancel;
use app\service\order\Profit;
use app\service\order\Refund;
use app\service\order\Stock;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\mini\model\StoreOrderLog;
use think\facade\Queue;
use think\facade\Log;

/**
 * @property int id
 * @property int order_id
 * @property int store_id
 * @property int $store_user_id 会员ID
 * @property int $salesman_id
 * @property int $company_id
 * @property string $no
 * @property int $order_status
 * @property string $remark
 * @property int $pay_type
 */
class StoreOrder extends Base
{


    /**
     * @param StoreOrder $model
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public static function onBeforeUpdate(StoreOrder $model): void
    {
        if ($order_status = request()->param('order_status', 0)) {
            //校验
            if($order_status == $model->getOrigin('order_status')) exception("订单已处理");
            //支付
            if ($model->order_status == 2 && $model->getOrigin('order_status') != 1) exception("订单状态异常,无法支付");
            //发货
            if ($model->order_status == 3 && $model->getOrigin('order_status') != 2) exception("订单状态异常,无法发货");
            //完成
            if ($model->order_status == 4 && $model->getOrigin('order_status') != 3) exception("订单状态异常,无法完成");
            //客户取消
            if ($model->order_status == 5 && !in_array($model->getOrigin('order_status'),[1,2])) exception("订单状态异常,无法取消");
            //商家取消发货
            if ($model->order_status == 6 && $model->getOrigin('order_status') != 2) exception("订单状态异常,无法取消发货");
            //添加订单日志
            (new StoreOrderLog())->add($model->id, $model->order_status);
            //发货
            if($model->order_status == 3){
                (new Stock($model))->update();//扣减库存
                //todo 经销商预收款产生的订单 没有分润
                (new Profit($model))->update();//分润
                //延迟队列 7天自动确认收货
                Queue::later(config('queue.order.confirm'), Confirm::class, ["order_id" => $model->id], "confirm");
            }
            //取消
            if(in_array($model->order_status,[5,6])){
                (new Cancel($model))->update();//退redis库存
                //有支付就退款
                if($model->getOrigin('order_status')  == 2){
                    (new Refund($model))->update();
                }
            }
            //完成
            if($model->order_status == 4){

            }
        }
    }

    /**
     * 删除前
     * @param StoreOrder $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(StoreOrder $model): void
    {
        if ($model->order_status > 2) exception("订单已支付/或已取消,无法删除");
    }

}